import { defineStore } from 'pinia';
import {
  getReviewStats,
  getReviewList,
  addReview,
  getReplyList,
  addReply,
  likeReview,
  unlikeReview,
  likeReply,
  unlikeReply,
  deleteReview
} from '../api/review.js';

export const useReviewStore = defineStore('review', {
  state: () => ({
    // 评价统计信息
    stats: {
      totalCount: 0,           // 评价总数
      averageRating: 0,        // 平均评分
      goodRatePercentage: 0,   // 好评率
      imageCount: 0,           // 有图评价数量
      qualityCount: 0,         // 优质评价数量
      starRating: 0,           // 星级评分
      goodCount: 0             // 好评数量
    },
    // 评价列表
    reviewList: [],
    // 回复列表（按评价ID分组）
    replyMap: {},
    // 点赞状态（评价ID -> 是否已点赞）
    likeStatus: {},
    // 回复点赞状态（回复ID -> 是否已点赞）
    replyLikeStatus: {},
    // 当前评价类型
    currentType: 0,
    // 加载状态
    loading: {
      list: false,
      stats: false,
      reply: false,
      action: false
    }
  }),

  getters: {
    // 获取评价统计
    getStats: (state) => state.stats,
    // 获取评价列表
    getReviews: (state) => state.reviewList,
    // 获取评价回复
    getReplies: (state) => (reviewId) => state.replyMap[reviewId] || [],
    // 获取评价点赞状态
    isReviewLiked: (state) => (reviewId) => state.likeStatus[reviewId] || false,
    // 获取回复点赞状态
    isReplyLiked: (state) => (replyId) => state.replyLikeStatus[replyId] || false,
    // 获取加载状态
    isLoading: (state) => (type) => state.loading[type]
  },

  actions: {
    // 加载评价统计
    async loadReviewStats(fruitId) {
      if (this.loading.stats) return;
      
      try {
        this.loading.stats = true;
        const res = await getReviewStats(fruitId);
        if (res.code === 200) {
          this.stats = {
            totalCount: res.data.totalCount || 0,
            averageRating: res.data.averageRating || 0,
            goodRatePercentage: res.data.goodRatePercentage || 0,
            imageCount: res.data.imageCount || 0,
            qualityCount: res.data.qualityCount || 0,
            starRating: res.data.starRating || 0,
            goodCount: res.data.goodCount || 0
          };
        }
        return res;
      } catch (error) {
        console.error('加载评价统计失败:', error);
        throw error;
      } finally {
        this.loading.stats = false;
      }
    },

    // 加载评价列表
    async loadReviewList(fruitId, type = 0) {
      if (this.loading.list) return;
      
      try {
        this.loading.list = true;
        this.currentType = type;
        
        const res = await getReviewList(fruitId, type);
        if (res.code === 200) {
          this.reviewList = res.data.map(review => ({
            ...review,
            showReplies: false,
            showReplyInput: false,
            replyContent: '',
            submitting: false
          }));
          
          // 初始化点赞状态
          this.reviewList.forEach(review => {
            this.likeStatus[review.id] = review.hasLiked || false;
          });
        }
        return res;
      } catch (error) {
        console.error('加载评价列表失败:', error);
        throw error;
      } finally {
        this.loading.list = false;
      }
    },

    // 加载评价回复
    async loadReplyList(reviewId) {
      if (this.loading.reply) return;
      
      try {
        this.loading.reply = true;
        const res = await getReplyList(reviewId);
        if (res.code === 200) {
          const replies = res.data.map(reply => ({
            ...reply,
            isLiked: reply.hasLiked || false,
            likeCount: reply.likes || 0
          }));
          this.replyMap[reviewId] = replies;
          
          // 更新评价中的回复数
          const review = this.reviewList.find(r => r.id === reviewId);
          if (review) {
            review.replyCount = replies.length;
          }
          
          // 初始化回复点赞状态
          replies.forEach(reply => {
            this.replyLikeStatus[reply.id] = reply.hasLiked || false;
          });
        }
        return res;
      } catch (error) {
        console.error('加载回复列表失败:', error);
        throw error;
      } finally {
        this.loading.reply = false;
      }
    },

    // 点赞/取消点赞评价
    async toggleReviewLike(reviewId) {
      if (!reviewId) {
        throw new Error('评论ID不能为空');
      }

      if (this.loading.action) return;
      this.loading.action = true;

      try {
        const isLiked = this.likeStatus[reviewId];
        const res = await (isLiked ? unlikeReview(reviewId) : likeReview(reviewId));

        if (res.code === 200) {
          // 更新点赞状态
          this.likeStatus[reviewId] = !isLiked;

          // 更新评价列表中的点赞数
          const review = this.reviewList.find(r => r.id === reviewId);
          if (review) {
            review.likes = (review.likes || 0) + (isLiked ? -1 : 1);
            review.hasLiked = !isLiked;
            review.isLiked = !isLiked; // 确保两个状态保持一致
          }
          return !isLiked;
        } else {
          throw new Error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('点赞/取消点赞评价失败:', error);
        throw error;
      } finally {
        this.loading.action = false;
      }
    },

    // 点赞/取消点赞回复
    async toggleReplyLike(replyId, reviewId) {
      if (!replyId || !reviewId) {
        throw new Error('回复ID和评论ID不能为空');
      }

      if (this.loading.action) return;
      this.loading.action = true;

      try {
        const isLiked = this.replyLikeStatus[replyId];
        const res = await (isLiked ? unlikeReply(replyId) : likeReply(replyId, reviewId));

        if (res.code === 200) {
          // 更新点赞状态
          this.replyLikeStatus[replyId] = !isLiked;

          // 更新回复列表中的点赞数
          const replies = this.replyMap[reviewId];
          if (replies) {
            const reply = replies.find(r => r.id === replyId);
            if (reply) {
              reply.likes = (reply.likes || 0) + (isLiked ? -1 : 1);
              reply.hasLiked = !isLiked;
              reply.isLiked = !isLiked; // 确保两个状态保持一致
              reply.likeCount = reply.likes;
            }
          }
          return !isLiked;
        } else {
          throw new Error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('点赞/取消点赞回复失败:', error);
        throw error;
      } finally {
        this.loading.action = false;
      }
    },

    // 提交回复
    async submitReply(replyDTO) {
      if (this.loading.action) return;
      
      try {
        this.loading.action = true;
        const res = await addReply(replyDTO);
        
        if (res.code === 200) {
          // 重新加载回复列表
          await this.loadReplyList(replyDTO.reviewId);
          
          // 更新评价的回复数
          const review = this.reviewList.find(r => r.id === replyDTO.reviewId);
          if (review) {
            review.replyCount = (review.replyCount || 0) + 1;
          }
        }
        return res;
      } catch (error) {
        console.error('提交回复失败:', error);
        throw error;
      } finally {
        this.loading.action = false;
      }
    },

    // 删除评价
    async deleteReview(reviewId) {
      if (this.loading.action) return;
      
      try {
        this.loading.action = true;
        const res = await deleteReview(reviewId);
        
        if (res.code === 200 && res.data) {
          // 从列表中移除评价
          const index = this.reviewList.findIndex(r => r.id === reviewId);
          if (index !== -1) {
            this.reviewList.splice(index, 1);
          }
          // 清理相关状态
          delete this.likeStatus[reviewId];
          delete this.replyMap[reviewId];
        }
        return res;
      } catch (error) {
        console.error('删除评价失败:', error);
        throw error;
      } finally {
        this.loading.action = false;
      }
    },

    // 重置评价数据
    resetReviewData() {
      this.stats = {
        totalCount: 0,
        averageRating: 0,
        goodRatePercentage: 0,
        imageCount: 0,
        qualityCount: 0,
        starRating: 0,
        goodCount: 0
      };
      this.reviewList = [];
      this.replyMap = {};
      this.likeStatus = {};
      this.replyLikeStatus = {};
      this.currentType = 0;
    },

    // 提交评价
    async submitReview(reviewDTO) {
      if (this.loading.action) return;
      
      try {
        this.loading.action = true;
        const res = await addReview(reviewDTO);
        
        if (res.code === 200) {
          // 重新加载评价列表
          await this.loadReviewList(reviewDTO.fruitDetailId);
        }
        return res;
      } catch (error) {
        console.error('提交评价失败:', error);
        throw error;
      } finally {
        this.loading.action = false;
      }
    }
  }
});
